const connect = require("../model");
const md5 = require("md5")
const config = require("../config")
// const config = require("../config")
const user = {
    async getlist(req, res) {
        let { page, size } = req.body
        page = (page - 1) * size
        let sql = 'select * from userinfo WHERE  `status` = 0  LIMIT  ? , ?'
        let [data] = await connect.query(sql, [page, size])
        res.json({
            code: 2000,
            data: data
        })
    }
    ,
    async edit(req, res) {
        let { id, name, password, newpassword, payimg, avatar } = req.body

        if (password && newpassword) {
            // 校验一下旧密码是否一致
            let sql = "select * from  userinfo where password = ? and id = ? "
            let [data] = await connect.query(sql, [md5(password + config.prived), id])
            if (data.length == 1) {
                //  密码正确
                let sql = "UPDATE userinfo set name= ? ,password =? , payimg = ? ,avatar =? where id =?   "
                await connect.query(sql, [name, md5(newpassword + config.prived), payimg, avatar, id])
                res.json({
                    code: 2000,
                    message: "修改成功"
                })
            } else {
                res.json({
                    code: 40002,
                    message: "新旧密码不一致"
                })
            }
        } else {
            let sql = "UPDATE userinfo set name= ?  , payimg = ? ,avatar =? where id =?   "
            await connect.query(sql, [name, payimg, avatar, id])
            res.json({
                code: 2000,
                message: "修改成功"
            })
        }

    },
    async userinfo(req, res) {
        let { lv } = req.session   // 这里的session 在哪产生 谁写的
        //  查询对方是什么角色
        let sql = "SELECT b.* from  role_menu  as a   LEFT JOIN menslist as b  on  a.menuid = b.id  WHERE roleid = ?  "
        let [data] = await connect.query(sql, [lv])

        res.json({
            code: 2000,
            data
        })
    },
    async orderdata(req, res) {
        let sql = "SELECT `status` , COUNT(*) AS num  , SUM(price) as total_price  FROM `order` GROUP BY  `status`; "
        let [data] = await connect.query(sql)
        res.json({
            code: 2000,
            data
        })
    }
}


module.exports = user